#!/usr/bin/env python
#coding:utf-8

import redis_connector as rediscon
import time
import redis_connector
from conf import hosts
import json


def push_configure_data_to_redis():
    '负责将hosts文件中的配置加载到REDIS服务器中'
    for h in hosts.monitored_hosts:
        config_dic = {}
        # rediscon.r['configurations::%s' % h.hostname] = []
        # print(h.services)
        for k,v in h.services.items():
            config_dic[k] = [v.interval, v.plugin_name, 0] # 0:first run-time
            #print('--->', k, v)
        # print config_dic
        redis_connector.r['HostConfiguration::%s' % h.hostname] = \
            json.dumps( config_dic)
        # print '*' * 20

channel = 'baoyj'
datadir = '/home/duanhq/Documents/python/mymodule/monitor/m_server/data/'

push_configure_data_to_redis()

msg_queue = rediscon.r.pubsub()  # bind listen instance
msg_queue.subscribe(channel)
# msg_queue.listen()

msg_queue.parse_response()

count = 0
while True:
    data = msg_queue.parse_response()
    rectime = time.time()
    data = json.loads(data[2])
    key = '%s::%s' % (data['hostname'], data['service_name'])
    rediscon.r[key] = json.dumps([rectime, data['data']])
    count += 1
    print(key, rediscon.r[key])
    print('-' * 20)
    if count % 1000 == 0:
        print count
